import { WebSocketGateway, WebSocketServer, SubscribeMessage, MessageBody, ConnectedSocket } from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';
import { CustomerServiceService } from './customer-service.service';
import { CreateMessageDto } from './dto/create-message.dto';

@WebSocketGateway({ namespace: '/customer-service', cors: true })
export class CustomerServiceGateway {
  @WebSocketServer()
  server: Server;

  constructor(private readonly csService: CustomerServiceService) {}

  // 客服/用户登录后绑定socketId
  @SubscribeMessage('register')
  handleRegister(@MessageBody() data: { userId?: number; agentId?: number }, @ConnectedSocket() client: Socket) {
    if (data.userId) {
      client.join('user_' + data.userId);
    }
    if (data.agentId) {
      client.join('agent_' + data.agentId);
    }
    return { success: true };
  }

  // 发送消息
  @SubscribeMessage('sendMessage')
  async handleSendMessage(@MessageBody() dto: CreateMessageDto) {
    const message = await this.csService.sendMessage(dto);
    // 推送给会话内所有相关用户/客服
    if (dto.userId) {
      this.server.to('user_' + dto.userId).emit('newMessage', message);
    }
    if (dto.agentId) {
      this.server.to('agent_' + dto.agentId).emit('newMessage', message);
    }
    return message;
  }
} 